<template>
  <div class="zj-goods">
    <van-search
        class="search-header"
        v-model="form.searchCtt"
        show-action
        label="商品名"
        background="#C81C22"
        placeholder="请输入商品名关键词"
        @search="onSearch"
        ref="searchRef"
        autocomplete="off"
        @focus="isSearchStatus = true"
    >
      <template #left>
        <van-icon @click="$router.replace('/home')" style="color:#fff;" name="arrow-left"/>
      </template>
      <template #action>
        <div style="color: #fff" @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!--  搜索界面  -->
    <div v-show="isSearchStatus" class="search-content">
      <!--   历史搜索   -->
      <div class="search-history" v-show="historySearchList.length">
        <SearchAbout @itemClick="handleHistorySearchClick" :contentItems="historySearchList">
          <template #rightIcon>
            <van-icon name="delete-o" @click="handleDeleteHistorySearch"/>
          </template>
        </SearchAbout>
      </div>
      <!--   推荐搜索   -->
      <div class="search-recommend" v-if="goodsModule.recommendSearchList.length">
        <SearchAbout
            title="搜索发现"
            @itemClick="handleRecommendSearchClick"
            :contentItems="goodsModule.recommendSearchList"
            :isShowData="isShowRecommend"
        >
          <template #rightIcon>
            <van-icon :name="isShowRecommend ? 'eye-o' : 'closed-eye'" @click="handleShowRecommend"/>
          </template>
        </SearchAbout>
      </div>
    </div>
    <!--  商品列表界面  -->
    <div v-show="!isSearchStatus" class="list-content">
      <!--   筛选和热门搜索   -->
      <div class="header">
        <div class="header-filter">
          <template v-for="(item, index) in filterItems" :key="item.key">
            <div :class="filterActive === index ? 'filter-item active' : 'filter-item'"
                 @click="handleFilterSearch(index, item.field)">
              <span>{{ item.label }}</span>
              <van-icon name="sort" v-if="item.field === 'price'"/>
            </div>
          </template>
          <div @click="handleOpenFilterDialog()">筛选</div>
        </div>
        <div class="header-sku">
          <div class="tip">热门搜索：</div>
          <template v-for="item in goodsModule.hotSearchList" :key="item.value">
            <div class="sku-item" @click="handleHotItemClick(item.value)">
              {{ item.value }}
            </div>
          </template>
        </div>
      </div>
      <!--   商品列表   -->
      <div v-show="goodsModule.searchGoodsList.length" class="content-main">
        <ZJScrollView
            ref="scrollViewRef"
            :wrapperConfig="scrollWrapperConfig"
        >
          <template #content>
            <div class="goods-list">
              <template v-for="item in goodsModule.searchGoodsList" :key="item.id">
                <div class="list-item" @click="handleGoodsItemClick(item.id)">
                  <div class="item-logo">
                    <img v-lazy="item.mainImage" alt="goods_img">
                  </div>
                  <div class="item-info">
                    <p class="info-detail">{{ item.name }}</p>
                    <p class="info-price">￥{{ item.price }}</p>
                  </div>
                </div>
              </template>
            </div>
            <div class="pullup-tips">
              <div v-if="!isPullUpLoad" class="before-trigger">
                <span class="pullup-txt" v-if="isFinish && goodsModule.searchGoodsList.length > 6">没有更多了</span>
                <span class="pullup-txt" v-if="!isFinish && goodsModule.searchGoodsList.length > 4">下拉加载更多</span>
              </div>
              <div v-else class="after-trigger">
                <span class="pullup-txt">加载中...</span>
              </div>
            </div>
            <div class="block" style="height: 8px;"></div>
          </template>
        </ZJScrollView>
      </div>
      <van-empty v-show="!goodsModule.searchGoodsList.length" description="暂无相关商品信息"/>
    </div>
    <!--  筛选侧边栏  -->
    <van-popup class="right-filter-dialog" v-model:show="isShowFilterDialog" position="right">
      <div class="dialog-item">
        <h3 class="item-title">分类</h3>
        <div class="item-tags">
          <template v-for="item in goodsModule.classificationList" :key="item.id">
            <span
                class="item"
                :class="form.categoryId === item.id && 'chosen'"
                @click="handleCategoryClick(item.id)"
            >
              {{ item.name }}
            </span>
          </template>
        </div>
      </div>
    </van-popup>
    <router-view/>
  </div>
</template>

<script setup lang="ts">
import {nextTick, onMounted, ref, watch} from "vue";
import {useRouter} from "vue-router";

import {IForm} from "@/views/ZJGoods/types";
import SearchAbout from "@/views/ZJGoods/SearchAbout/SearchAbout.vue";
import ZJScrollView from "@/components/ZJScrollView/ZJScrollView.vue";
import useGoodsModule from "@/store/goodsModule";
import {filterItems, scrollWrapperConfig} from "./config"
import {localCache} from "@/utils";

// 变量初始化
const router = useRouter()
const scrollViewRef = ref<InstanceType<typeof ZJScrollView>>()
const goodsModule = useGoodsModule()
// 历史搜索的处理、热门搜索
const historySearchList = ref<Array<string>>([])
// 清除历史搜索
const handleDeleteHistorySearch = () => {
  historySearchList.value = []
  localCache.setCache("history_search", "")
}
// 热门搜索
const handleHotItemClick = async (searchCtt: string) => {
  form.value.searchCtt = searchCtt
  await goodsModule.setSearchGoodsAction(form.value)
  scrollViewRef.value.bs.refresh()
}

const isSearchStatus = ref(false)
const form = ref<IForm>({
  pageNum: 1,
  pageSize: 6,
  searchCtt: "",
  orderByColumn: "",
  isDesc: "",
  categoryId: 0,
  isGlobalSearch: 1
})
// 全局搜索
const onSearch = async () => {
  form.value.pageNum = 1
  isFinish.value = false
  scrollViewRef.value.bs.scrollTo(0, 0)
  scrollViewRef.value.bs.closePullUp()
  //  添加到历史搜索里面, 12个
  if (form.value.searchCtt) { // 空搜索不加
    historySearchList.value.unshift(form.value.searchCtt as string)
  }
  // 去重
  historySearchList.value = Array.from(new Set(historySearchList.value))
  // 取前12
  historySearchList.value = historySearchList.value.slice(0, 12)
  localCache.setCache("history_search", historySearchList.value.slice(0, 12))
  isSearchStatus.value = false
  await goodsModule.setSearchGoodsAction(form.value)
  if (goodsModule.searchGoodsList.length) {
    scrollViewRef.value.bs.refresh()
    scrollViewRef.value.bs.openPullUp({})
  }
}
// 点击不同按钮筛选不同商品
const priceFilterDesc = ref("asc")
const filterActive = ref(0)
const handleFilterSearch = async (index = 0, field = "", isDesc = "") => {
  // 可能在其他页面已经请求完所有了
  isFinish.value = false
  form.value.pageNum = 1
  scrollViewRef.value.bs.scrollTo(0, 0)
  scrollViewRef.value.bs.closePullUp()
  // 可以有升序降序两种排序的字段
  const twiceFilter = ["price"]
  // 如果不是两种排序，重复点击的话不请求
  if (filterActive.value === index && !twiceFilter.includes(field)) return
  filterActive.value = index
  form.value.orderByColumn = field
  form.value.isDesc = isDesc
  if (field === "price") { // 如果是价格, 每次点击都会切换排序顺序
    form.value.isDesc = priceFilterDesc.value
    priceFilterDesc.value = priceFilterDesc.value === "asc" ? "desc" : "asc"
  }
  await goodsModule.setSearchGoodsAction(form.value)
  scrollViewRef.value.bs.refresh()
  scrollViewRef.value.bs.openPullUp({})
}
// 传递给历史搜索SearchAbout的
const handleHistorySearchClick = async (searchCtt: string) => {
  form.value.searchCtt = searchCtt
  await onSearch()
}
// 传递给搜索发现SearchAbout的
const handleRecommendSearchClick = async (searchCtt: string) => {
  form.value.searchCtt = searchCtt
  await onSearch()
}
// 打开筛选侧边栏
const isShowFilterDialog = ref(false)
const handleOpenFilterDialog = async () => {
  isShowFilterDialog.value = true
  await goodsModule.setClassificationAction()
}
// 筛选侧边栏的点击
const handleCategoryClick = async (categoryId: number) => {
  filterActive.value = 0
  form.value.pageNum = 1
  scrollViewRef.value.bs.scrollTo(0, 0)
  scrollViewRef.value.bs.closePullUp()
  if (form.value.categoryId === categoryId) { // 再次点击取消选中
    form.value.categoryId = 0
    form.value.isGlobalSearch = 1
  } else {
    form.value.categoryId = categoryId
    delete form.value.isGlobalSearch
  }
  await goodsModule.setSearchGoodsAction(form.value)
  nextTick(() => {
    scrollViewRef.value.bs.refresh()
    scrollViewRef.value.bs.openPullUp({})
  })
}

// 搜索发现数据隐藏显示
const isShowRecommend = ref(true)
const handleShowRecommend = () => {
  isShowRecommend.value = !isShowRecommend.value
}

// 商品的点击
const handleGoodsItemClick = (goodsId: number) => {
  router.push("/goods/detail/" + goodsId)
}

// 上拉加载更多
const isPullUpLoad = ref(false)
const isFinish = ref(true)
const searchRef = ref<HTMLElement>()
onMounted(async () => {
  const localHistorySearchItems = localCache.getCache("history_search")
  if (localHistorySearchItems) {
    historySearchList.value = localHistorySearchItems
  }
  // 搜索发现
  await goodsModule.setRecommendSearch()
  // 热门搜索的
  await goodsModule.setHotSearchAction()
  // 触底刷新
  scrollViewRef.value.bs.on('pullingUp', async () => {
    const currentTotal = goodsModule.searchGoodsList.length
    const pageTotal = goodsModule.searchGoodsPageInfo.pageTotal
    if (currentTotal >= pageTotal) {
      isFinish.value = true
      return
    }
    isPullUpLoad.value = true
    form.value.pageNum && (form.value.pageNum += 1)
    await goodsModule.setSearchGoodsAction({
      ...form.value,
      isMoreMode: true
    })
    console.log(222)
    scrollViewRef.value.bs.finishPullUp()
    scrollViewRef.value.bs.refresh()
    isPullUpLoad.value = false
  })
  await nextTick(() => {
    searchRef.value?.focus()
  })
})

watch(isSearchStatus, async newValue => {
  if (newValue) {
    // 搜索发现数据重置
    await goodsModule.setRecommendSearch()
  }
})
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.zj-goods {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 889;
  background-color: @theme-grey-color;

  .search-header {
    padding-left: 8px;
    height: 50px;
  }

  .search-content {
    height: calc(100% - 50px);
    padding: 16px;
    background: linear-gradient(to bottom, #fff, @theme-grey-color);
  }

  .list-content {
    height: calc(100% - 50px);
    background-color: #fff;

    .header {

      .header-filter {
        display: flex;
        height: 40px;
        align-items: center;
        font-size: 14px;
        justify-content: space-between;
        border-bottom: 1px solid #f2f2f2;
        padding: 0 8px;
        box-sizing: border-box;

        .filter-item {
          &.active {
            color: #C81C22;
          }
        }

        & > div {
          &.active {
            color: @theme-color;
          }
        }
      }

      .header-sku {
        display: flex;
        font-size: 14px;
        height: 30px;
        align-items: center;
        border-bottom: 1px solid #f2f2f2;
        padding: 0 8px;
        box-sizing: border-box;

        .tip {
          color: @theme-color;
        }

        .sku-item {
          margin-left: 8px;
        }
      }
    }

    .content-main {
      height: calc(100% - 70px);
      overflow: hidden;
      background-color: @theme-grey-color;

      .goods-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        padding: 0 8px;
        margin-top: 8px;

        .list-item {
          width: 49%;
          border-radius: 10px;
          background-color: #fff;
          overflow: hidden;
          margin-bottom: 8px;
          display: flex;
          flex-direction: column;

          .item-logo {
            height: 180px;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .item-info {
            padding: 8px 4px;
            font-size: 14px;
            display: flex;
            flex-direction: column;
            flex: 1;

            .info-detail {
              word-break: break-all;
              flex: 1;
            }

            .info-price {
              color: @theme-color;
              font-weight: 600;
            }
          }
        }
      }

      .pullup-tips {
        text-align: center;

        .pullup-txt {
          color: #999;
        }
      }
    }
  }

  :deep(.right-filter-dialog) {
    width: 250px;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;

    .dialog-item {
      .item-title {
        font-weight: 400;
        margin-bottom: 10px;
        font-size: 16px;
      }

      .item-tags {
        display: flex;
        flex-wrap: wrap;

        .item {
          margin: 0 14px 14px 0;
          flex-shrink: 0;
          padding: 8px 16px;
          border-radius: 25px;
          background-color: #f2f2f2;
          font-size: 14px;
          border: 1px solid #f2f2f2;

          &.chosen {
            font-weight: 600;
            border: 1px solid #C81C22;
            background-color: #FFF9F9;
            color: #C81C22;
          }
        }
      }
    }
  }
}
</style>
